<template>
    <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <el-alert type="warning" :closable="false" show-icon>
          注意: 只允许为第三级分类设置相关参数!
        </el-alert>
          <el-row>
            <el-col>
              <span>选择商品分类:</span>
              <el-cascader expand-trigger="hover"
              :options="paramsData" :props="paramsProps"
              v-model="selectedOptions"
              @change="paramsChange">
              </el-cascader>
              <!-- 标签页区域 -->
              <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 动态参数页签 -->
                <el-tab-pane label="动态参数" name="many">
                  <!-- 动态添加按钮 -->
                  <el-button type="primary" size="mini" :disabled="getBtn"
                  @click="paramsDialogVisible=true">添加参数</el-button>
                  <!-- 动态参数表格 -->
                  <el-table :data="manyTableData" border stripe>
                    <!-- 展开列 -->
                    <el-table-column type="expand">
                      <template slot-scope="scope">
                        <div class="tagleft">
                          <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable
                          @close="handleClose(i, scope.row)" class="tagright">
                            {{item}}
                          </el-tag>
                          <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInputRef"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                          </el-input>
                          <el-button class="button-new-tag" size="small"
                          @click="showInput(scope.row)" v-else>
                          + New Tag</el-button>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column type="index" label="#">
                    </el-table-column>
                    <el-table-column prop="attr_name" label="参数名称">
                    </el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                        @click="editTableData(scope.row.attr_id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                        @click="deletedTableData(scope.row.attr_id)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <!-- 静态属性页签 -->
                <el-tab-pane label="静态属性" name="only">
                  <!-- 静态添加按钮 -->
                  <el-button type="primary" size="mini" :disabled="getBtn"
                  @click="paramsDialogVisible=true">添加属性</el-button>
                  <!-- 静态属性表格 -->
                  <el-table :data="onlyTableData" border stripe>
                    <!-- 展开行 -->
                    <el-table-column type="expand">
                      <template slot-scope="scope">
                        <div class="tagleft">
                          <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable
                          @close="handleClose(i, scope.row)" class="tagright">
                            {{item}}
                          </el-tag>
                          <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInputRef"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                          </el-input>
                          <el-button class="button-new-tag" size="small"
                          @click="showInput(scope.row)" v-else>
                          + New Tag</el-button>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column type="index" label="#">
                    </el-table-column>
                    <el-table-column prop="attr_name" label="属性名称">
                    </el-table-column>
                    <el-table-column label="操作">
                      <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                        @click="editTableData(scope.row.attr_id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                        @click="deletedTableData(scope.row.attr_id)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
      </el-card>
      <!-- 添加参数对话框 -->
      <el-dialog :title="'添加' + addData"
      :visible.sync="paramsDialogVisible"
      width="50%" @closed="paramsClosed">
        <el-form :model="addParams" :rules="paramsRules" ref="paramsRef"
        label-width="80px">
          <el-form-item :label="addData" prop="attr_name">
            <el-input v-model="addParams.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="paramsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsData">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数对话框 -->
      <el-dialog :title="'修改' + addData"
      :visible.sync="editDialogVisible"
      width="50%" @closed="editClosed">
        <el-form :model="editParams" :rules="editRules" ref="editRef"
        label-width="80px">
          <el-form-item :label="addData" prop="attr_name">
            <el-input v-model="editParams.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParamsData">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据
      paramsData: [],
      // 级联选择器配置
      paramsProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器被选中的id数组
      selectedOptions: [],
      // 控制标签页绑定哪一页(根据el-tab-pane的name属性确定)
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 控制添加对话框的显示和隐藏
      paramsDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 添加对话框绑定的数据
      addParams: {
        attr_name: ''
      },
      // 修改对话框绑定的数据
      editParams: {},
      // 添加的表单校验规则
      paramsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改的表单校验规则
      editRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getParamsList()
  },
  methods: {
    // 获取级联选择器绑定商品参数数据
    async getParamsList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.paramsData = res.data
    },
    // 监听级联选择器selectedOptions数组改变事件
    paramsChange() {
      // 商品分类级联选择器发生变化时重新获取数据
      this.getParamsData()
    },
    // 监听tab页签改变事件
    handleTabClick() {
      // 改变页签重新获取数据
      this.getParamsData()
    },
    // 获取动态静态参数属性数据
    async getParamsData() {
      // 只允许选中三级参数
      // 当数组长度不等于3时清空数组
      if (this.selectedOptions.length !== 3) {
        this.selectedOptions = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      // 选中三级分类发送请求获取静态和动态的参数数据
      const { data: res } = await this.$http.get(`categories/${this.selectedOptions[2]}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      console.log(res.data)
      // 赋值之前先把展开列的数据字符串转换成数组
      res.data.forEach(item => {
        // 控制 + New Tag 切换
        item.inputVisible = false
        // 双向绑定 + New Tag 输入框的值
        item.inputValue = ''
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      // 判断activeName的值为many时为动态参数否则为静态属性
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听添加对话框的关闭事件
    paramsClosed() {
      this.$refs.paramsRef.resetFields()
    },
    // 监听修改对话框的关闭事件
    editClosed() {
      this.$refs.editRef.resetFields()
    },
    // 监听添加对话框的确定按钮事件
    addParamsData() {
      this.$refs.paramsRef.validate(async valid => {
        if (!valid) return this.$message.error('添加失败')
        const { data: res } = await this.$http.post(`categories/${this.selectedOptions[2]}/attributes`, {
          attr_name: this.addParams.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加成功')
        this.getParamsData()
        this.paramsDialogVisible = false
      })
    },
    // 监听操作列的编辑按钮事件
    async editTableData(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.selectedOptions[2]}/attributes/${id}`,
        {
          params: { attr_sel: this.activeName }
        })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      this.editParams = res.data
    },
    // 监听操作列的删除按钮事件
    async deletedTableData(id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '删除参数', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果确定删除返回值为 'confirm'
      if (result !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(`categories/${this.selectedOptions[2]}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParamsData()
    },
    // 监听修改对话框的确定按钮事件
    editParamsData() {
      this.$refs.editRef.validate(async valid => {
        if (!valid) return this.$message.error('修改参数失败1')
        const { data: res } = await this.$http.put(`categories/${this.selectedOptions[2]}/attributes/${this.editParams.attr_id}`,
          {
            attr_name: this.editParams.attr_name,
            attr_sel: this.activeName
          })
        if (res.meta.status !== 200) return this.$message.error('修改参数失败2')
        this.$message.success('修改参数成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 文本框失去焦点时或摁下了 Enter 都会触发
    handleInputConfirm(row) {
      // 判断文本框是否输入了值，没有就重置，有就push到数组中并发送请求添加后端数据
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return false
      }
      // 浏览器页面添加完毕
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      // 更新后端数据
      this.saveAttrVals(row)
    },
    // 参数改变时更新后端数据
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.selectedOptions[2]}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
      this.$message.success('修改参数项成功')
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    },
    // 监听tag标签删除事件
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      // 更新后端数据
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 控制级联选择器disabled值
    getBtn() {
      if (this.selectedOptions.length === 3) return false
      return true
    },
    // 动态控制添加参数还是属性
    addData() {
      if (this.activeName === 'many') return '动态参数'
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 20px;
}
.el-cascader {
  margin-left: 10px;
}
.tagleft {
  margin-left: 60px;
}
.tagright {
  margin-right: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
